package com.yami.shop.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.yami.shop.bean.model.AttachFile;
import com.yami.shop.common.util.Json;
import com.yami.shop.dao.AttachFileMapper;
import com.yami.shop.service.AttachFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Date;

@Slf4j
@Service
public class LocalStorageAttachFileServiceImpl extends ServiceImpl<AttachFileMapper, AttachFile> implements AttachFileService {

    @Autowired
    private AttachFileMapper attachFileMapper;


    public final static String NORM_MONTH_PATTERN = "yyyy/MM/";

    @Value("${app.uploadPath}")
    public String filepath;



    @Override
    @Transactional(rollbackFor = Exception.class)
    public String uploadFile(byte[] bytes,String originalName){
        String extName = FileUtil.extName(originalName);
        String fileName = DateUtil.format(new Date(), NORM_MONTH_PATTERN)+ IdUtil.simpleUUID() + "." + extName;


        AttachFile attachFile = new AttachFile();
        attachFile.setFilePath(fileName);
        attachFile.setFileSize(bytes.length);
        attachFile.setFileType(extName);
        attachFile.setUploadTime(new Date());
        attachFileMapper.insert(attachFile);



        File saveFile = new File(filepath+'/'+fileName);
        if(!FileUtil.exist(saveFile.getParentFile())){
            saveFile.getParentFile().mkdirs();
        }
        if(!FileUtil.exist(saveFile)){
            try {

                saveFile.createNewFile();
            } catch (IOException e) {
                log.info(e.getLocalizedMessage());
            }
        }

        FileOutputStream fs= null;
        try {
            fs = new FileOutputStream(saveFile);
            fs.write(bytes);
            fs.close();
        } catch (FileNotFoundException e) {
//            e.printStackTrace();
            log.info(e.getLocalizedMessage());
        } catch (IOException e) {
//            e.printStackTrace();
            log.info(e.getLocalizedMessage());

        }


        return fileName;
    }

    @Override
    public void deleteFile(String fileName){
        attachFileMapper.delete(new LambdaQueryWrapper<AttachFile>().eq(AttachFile::getFilePath,fileName));
        FileUtil.del(filepath+'/'+fileName);

    }


}
